package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.common.UserHolder;
import com.itheima.ydd.dto.CateDto;
import com.itheima.ydd.entity.*;
import com.itheima.ydd.service.*;
import com.itheima.ydd.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 后台管理
 */
@RestController
@Slf4j
@RequestMapping("index")
public class IndexController {

	@Autowired
	private UserService userService;

	@Autowired
	private ConfigService configService;

	@Autowired
	private ArticleService articleService;

	@Autowired
	private CateService cateService;

	@Autowired
	private AdvposService advposService;

	@Autowired
	private AdvimgService advimgService;

	@Autowired
	private TagService tagService;
	
	@Autowired
	private YddUserService yddUserService;



	/**
	 * 用户登录
	 *
	 * @param user
	 * @return
	 */
	@PostMapping("login")
	public ResultData login(@RequestBody User user) {
		log.info("用户信息: 邮箱:{},密码:{}", user.toString());

		LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(User::getLogin_name, user.getLogin_name());
		queryWrapper.eq(User::getPassword, DigestUtils.md5Hex(user.getPassword()));
		User loginUser = userService.getOne(queryWrapper);

		if (loginUser == null) {
			throw new BusinessException("登录失败!");
		}

		Map retMap = new HashMap();
		Map tokenMap = new HashMap<>();
		// 登录成功
		if (loginUser != null) {
			// 生成token信息
			String roleId = loginUser.getRole_id()
					.replace("[", "")
					.replace("]", "")
					.replace("\"", "");

			tokenMap.put("id", loginUser.getId());
			tokenMap.put("roleId", roleId);

			String token = JwtUtils.getToken(tokenMap);
			retMap.put("token", token);

		}
		return ResultData.ok("", retMap);
	}


	/**
	 * 获取系统配置
	 *
	 * @return
	 */
	@GetMapping("getConfig")
	public ResultData getConfig() {
		List<Config> list = configService.list();

		Map<String, String> map = new HashMap<>();
		for (Config config : list) {
			map.put(config.getAttr_key(), config.getAttr_value());
		}
		return ResultData.ok("", map);
	}

	/**
	 * 获取用户资料
	 *
	 * @param
	 * @return
	 */
	@PostMapping("profile")
	public ResultData profile() {
		Map<String, Object> map = configService.profile();
		return ResultData.ok("", map);
	}

	/**
	 * 登出
	 */
	@PostMapping("/logout")
	public void logout() {
		//删除用户信息
		UserHolder.remove();
	}

	/**
	 * 主页统计信息
	 * @return
	 */
	@GetMapping("baseInfo")
	public ResultData baseInfo() {
		List<Cate> all_cate = cateService.list();
		List<CateDto> all_cateDto = new ArrayList<>();
		all_cateDto = all_cate.stream().map(item -> {
			CateDto cateDto = new CateDto();
			BeanUtils.copyProperties(item, cateDto);
			LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(Article::getCateid,item.getId());
			int count = articleService.count(lambdaQueryWrapper);
			cateDto.setNum(count);
			return cateDto;
		}).collect(Collectors.toList());
		int advpos_num = advposService.count();
		int tag_num = tagService.count();
		int admin_num = userService.count();
		int article_num = articleService.count();
		int cate_num = cateService.count();
		int advimg_num = advimgService.count();
		LambdaQueryWrapper<YddUser> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
		userLambdaQueryWrapper.orderByDesc(YddUser::getId);
		userLambdaQueryWrapper.select(YddUser::getId,YddUser::getUsername,YddUser::getSex,YddUser::getIcon,YddUser::getAddress);
		userLambdaQueryWrapper.last("limit 5");
		List<YddUser> new_user = yddUserService.list(userLambdaQueryWrapper);
		LambdaQueryWrapper<Article> articleLambdaQueryWrapper = new LambdaQueryWrapper<>();
		articleLambdaQueryWrapper.orderByDesc(Article::getClick);
		articleLambdaQueryWrapper.select(Article::getId,Article::getTitle,Article::getAuthor,Article::getKeywords,Article::getClick);
		List<Article> hot_article = articleService.list(articleLambdaQueryWrapper);
		int total = userService.count();
		LambdaQueryWrapper<YddUser> yddUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
		yddUserLambdaQueryWrapper.eq(YddUser::getSex,0);
		int user_woman = yddUserService.count(yddUserLambdaQueryWrapper);
		LambdaQueryWrapper<YddUser> yddUserLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
		yddUserLambdaQueryWrapper1.eq(YddUser::getSex,1);
		int user_man = yddUserService.count(yddUserLambdaQueryWrapper1);
		Map<String, Object> map = new HashMap<>();
		map.put("all_cate",all_cateDto);
		map.put("advpos_num",advpos_num);
		map.put("tag_num",tag_num);
		map.put("admin_num",admin_num);
		map.put("article_num",article_num);
		map.put("cate_num",cate_num);
		map.put("advimg_num",advimg_num);
		map.put("new_user",new_user);
		map.put("hot_article",hot_article);
		Map<String, Object> userMap = new HashMap<>();
		userMap.put("total",total);
		userMap.put("user_woman",user_woman);
		userMap.put("user_man",user_man);
		map.put("user",userMap);
		return ResultData.ok("",map);
	}
}
